import { data, directive } from '../ee-directive'
import { prevent } from '../__use/dom'

/** binding.value
 * @typedef {object} value
 * @property {boolean} value - 是否需要遮罩
 * @property {boolean} full - 是否全屏
 * @property {boolean} scrollable - 是否允许滚动
 * @property {boolean} hidden - 是否不展示遮罩
 */

/** binding.modifiers
 * @typedef {object} modifiers
 * @property {boolean} full - 是否全屏
 * @property {boolean} scrollable - 是否允许滚动
 * @property {boolean} hidden - 是否不展示遮罩
 */

/** el.__overlay
 * @typedef {object} overlaydata
 */

// 以下注释可以忽略
/** binding
 * @typedef {object} binding
 * @property {value} value
 * @property {string | string[]} [arg] - 没有可以删掉
 * @property {modifiers} modifiers - 没有可以删掉
 */
/** el
 * @typedef {HTMLElement | {__overlay: data | overlaydata}} el
 */

export default directive({
  name: 'overlay',
  /**
   * @param {el} el
   * @param {binding} binding
   */
  delete(el, binding) {
    if (binding.value)
      binding.value.value = 0;
  },
  /**
   * @param {el} el
   * @param {binding} binding
   */
  change(el, binding, vnode, prevVnode) {
    const modifier = Object.assign({}, binding.modifiers, binding.value);
    const parent = modifier.full ? document.body : el.parentElement;
    const data = el.__overlay;
    if (binding.value?.value) {
      el.classList.add('overlay');
      // full变化引起parent发生变化
      if (modifier.full != data.clone.value?.full)
        (!modifier.full ? document.body : el.parentElement).classList.remove('overlay-parent');
      if (modifier.full)
        el.classList.add('full');
      else
        el.classList.remove('full');
      if (modifier.hidden)
        el.classList.add('hidden');
      else
        el.classList.remove('hidden');
      if (modifier.scrollable) {
        parent?.classList.remove('overlay-parent');
        el.removeEventListener('touchmove', prevent);
        el.removeEventListener('wheel', prevent);
      } else {
        parent?.classList.add('overlay-parent');
        el.addEventListener('touchmove', prevent);
        el.addEventListener('wheel', prevent);
      }
    } else {
      // el.classList.remove('overlay', 'full', 'hidden');
      el.removeEventListener('touchmove', prevent);
      el.removeEventListener('wheel', prevent);
      parent?.classList.remove('overlay-parent');
    }
  },
})